<template>
	<view class="contaier" :style="{ minHeight: getHeight + 'px' }">
		<cu-custom bgColor="bg-gradual-blue" :isBack="true">
			<block slot="backText">返回</block>
			<block slot="content">匹兹堡睡眠质量指数（PSQI）</block>
		</cu-custom>
		
		<view style="height: 250rpx;width: 1rpx;"></view>
		<!-- 答题主页面 -->
		<view class="padding">
			<view class="mainBox radius shadow-warp bg-white margin-top relative">
				<view class="userHeard cu-avatar lg round" style="background-image:url(http://cdn.zhoukaiwen.com/logo.png);"></view>
				<view v-show="hasData">
					<view class="animation-reverse shadow" :class="animation" data-class="slide-rights" v-if="DataList[num].serialNumber">
						<view class="mentalTitle text-xl text-black text-bold">
							<text>{{ DataList[num].serialNumber || '' }}</text>
							<text>、</text>
							<text>{{ DataList[num].title || '' }}</text>
						</view>
						<view v-if="DataList[num].serialNumber === '1' || DataList[num].serialNumber === '3' || DataList[num].serialNumber === '4'">
							<picker @change="pickerChange" :value="pickerIndex" :range="pickerRange">
								<view class="picker">
									{{ pickerRange[pickerIndex] }}
								</view>
							</picker>
						</view>
						<view v-else class="mentalList" v-for="(item, index) in DataList[num].itemList" v-bind:class="{ mentalListActive: index == mentalListActive }"
						 @tap="Toggle(index)">
							<view @click="answerchoose(DataList[num].serialNumber,index,item.answer)">
								<view class="indexBox text-shadow" >{{ item.number || '' }}</view>
								{{ item.answer || '' }}
							</view>
						</view>
					</view>

					<u-line color="#dddddd"></u-line>

					<view class="margin-top cu-progress radius striped active">
						<view class="bg-blue" :style="[{ width: loading ? progress + '%' : '' }]">{{  progress }}%</view>
					</view>
					<view class="explainMain">本测试仅提供参考（答题自动保存在本地，支持中途退出）</view>
					<!-- {{useranswers}} -->
				</view>

				<view v-show="noData">
					<view class="text-center text-bold text-black text-xxl margin-tb-xl">您已答题，感谢参与</view>
					<view class="text-center margin-tb-lg text-lg"><h3>IIMedGPT评测结果：</h3>来源：总分：{{showMessage.total_score}}分，睡眠质量：{{showMessage.sleep_quality}}，各项分数：{{formatComponentScores(showMessage.component_scores)}}分</view>
				</view>
			</view>
		</view>

		<view class="explain">
			<view @click="goExplain">
				<u-icon name="question-circle-fill" size="30"></u-icon>
				答题规则说明
			</view>
		</view>

		<!-- 遮罩层 -->
		<u-mask :show="show">
			<view class="warp">
				<view class="rect" @tap.stop>
					<view class="closeBtn">
						<u-icon @click="closeMask" name="close-circle-fill" color="#ccc" size="58"></u-icon>
					</view>

					<view class="closeImg">
						<image mode="aspectFit" src="http://cdn.zhoukaiwen.com/answerTrophy.png"></image>
					</view>
					<view class="text-black text-bold text-center">恭喜您！完成答题！</view>
					<view class="text-center margin-tb-lg text-gray">总分：{{showMessage.total_score}}分，睡眠质量：{{showMessage.sleep_quality}}，各项分数：{{formatComponentScores(showMessage.component_scores)}}</view>
				</view>
			</view>
		</u-mask>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				show: false,
				getHeight: '',
				loading: false,
				animation: '',
				mentalListActive: -1,
				noData: false,
				hasData: true,
				num: 0,
				DataList: [
					{
						"serialNumber": "1",
						"name": "匹兹堡睡眠质量指数（PSQI）",
						"title": "近 1 个月，晚上上床通常在 --- 点钟",
						"itemList": []
					},
					{
						"serialNumber": "2",
						"name": "匹兹堡睡眠质量指数（PSQI）",
						"title": "近1个月，从上床到入睡通常需要---min",
						"itemList": [
							{"number": "A", "answer": "≤15min"},
							{"number": "B", "answer": "16-30min"},
							{"number": "C", "answer": "31-60min"},
							{"number": "D", "answer": "≥60min"}
						]
					},
					{
						"serialNumber": "3",
						"name": "匹兹堡睡眠质量指数（PSQI）",
						"title": "近1个月，通常早上---点起床",
						"itemList": []
					},
					{
						"serialNumber": "4",
						"name": "匹兹堡睡眠质量指数（PSQI）",
						"title": "近1个月，每夜通常实际睡眠---h(不等于卧床时间)",
						"itemList": []
					},
					{
						"serialNumber": "5a",
						"name": "匹兹堡睡眠质量指数（PSQI）",
						"title": "近1个月，因入睡困难(30min内不能入睡)影响睡眠而烦恼",
						"itemList": [
							{ "number": "A", "answer": "无" },
							{ "number": "B", "answer": "<1次/周" },
							{ "number": "C", "answer": "1-2次/周" },
							{ "number": "D", "answer": "≥3次/周" }
						]
					},
					{
						"serialNumber": "5b",
						"name": "匹兹堡睡眠质量指数（PSQI）",
						"title": "近1个月，因夜间易醒或早醒影响睡眠而烦恼",
						"itemList": [
							{ "number": "A", "answer": "无" },
							{ "number": "B", "answer": "<1次/周" },
							{ "number": "C", "answer": "1-2次/周" },
							{ "number": "D", "answer": "≥3次/周" }
						]
					},
					{
						"serialNumber": "5c",
						"name": "匹兹堡睡眠质量指数（PSQI）",
						"title": "近1个月，因夜间去厕所影响睡眠烦恼",
						"itemList": [
							{ "number": "A", "answer": "无" },
							{ "number": "B", "answer": "<1次/周" },
							{ "number": "C", "answer": "1-2次/周" },
							{ "number": "D", "answer": "≥3次/周" }
						]
					},
					{
						"serialNumber": "5d",
						"name": "匹兹堡睡眠质量指数（PSQI）",
						"title": "近1个月，因呼吸不畅影响睡眠烦恼",
						"itemList": [
							{ "number": "A", "answer": "无" },
							{ "number": "B", "answer": "<1次/周" },
							{ "number": "C", "answer": "1-2次/周" },
							{ "number": "D", "answer": "≥3次/周" }
						]
					},
					{
						"serialNumber": "5e",
						"name": "匹兹堡睡眠质量指数（PSQI）",
						"title": "近1个月，因咳嗽或鼾声高影响睡眠而烦恼",
						"itemList": [
							{ "number": "A", "answer": "无" },
							{ "number": "B", "answer": "<1次/周" },
							{ "number": "C", "answer": "1-2次/周" },
							{ "number": "D", "answer": "≥3次/周" }
						]
					},
					{
						"serialNumber": "5f",
						"name": "匹兹堡睡眠质量指数（PSQI）",
						"title": "近1个月，因感觉冷影响睡眠而烦恼",
						"itemList": [
							{ "number": "A", "answer": "无" },
							{ "number": "B", "answer": "<1次/周" },
							{ "number": "C", "answer": "1-2次/周" },
							{ "number": "D", "answer": "≥3次/周" }
						]
					},
					{
						"serialNumber": "5g",
						"name": "匹兹堡睡眠质量指数（PSQI）",
						"title": "近1个月，因感觉热影响睡眠而烦恼",
						"itemList": [
							{ "number": "A", "answer": "无" },
							{ "number": "B", "answer": "<1次/周" },
							{ "number": "C", "answer": "1-2次/周" },
							{ "number": "D", "answer": "≥3次/周" }
						]
					},
					{
						"serialNumber": "5h",
						"name": "匹兹堡睡眠质量指数（PSQI）",
						"title": "近1个月，因做噩梦影响睡眠而烦恼",
						"itemList": [
							{ "number": "A", "answer": "无" },
							{ "number": "B", "answer": "<1次/周" },
							{ "number": "C", "answer": "1-2次/周" },
							{ "number": "D", "answer": "≥3次/周" }
						]
					},
					{
						"serialNumber": "5i",
						"name": "匹兹堡睡眠质量指数（PSQI）",
						"title": "近1个月，因疼痛不适影响睡眠而烦恼",
						"itemList": [
							{ "number": "A", "answer": "无" },
							{ "number": "B", "answer": "<1次/周" },
							{ "number": "C", "answer": "1-2次/周" },
							{ "number": "D", "answer": "≥3次/周" }
						]
					},
					{
						"serialNumber": "5j",
						"name": "匹兹堡睡眠质量指数（PSQI）",
						"title": "近1个月，因其他事情影响睡眠而烦恼",
						"itemList": [
							{ "number": "A", "answer": "无" },
							{ "number": "B", "answer": "<1次/周" },
							{ "number": "C", "answer": "1-2次/周" },
							{ "number": "D", "answer": "≥3次/周" }
						]
					},
					{
						"serialNumber": "6",
						"name": "匹兹堡睡眠质量指数（PSQI）",
						"title": "近1个月，总的来说，您认为您的睡眠质量：",
						"itemList": [
							{ "number": "A", "answer": "很好" },
							{ "number": "B", "answer": "较好" },
							{ "number": "C", "answer": "较差" },
							{ "number": "D", "answer": "很差" }
						]
					},
					{
						"serialNumber": "7",
						"name": "匹兹堡睡眠质量指数（PSQI）",
						"title": "近1个月，您用药物催眠的情况：",
						"itemList": [
							{ "number": "A", "answer": "无" },
							{ "number": "B", "answer": "<1次/周" },
							{ "number": "C", "answer": "1-2次/周" },
							{ "number": "D", "answer": "≥3次/周" }
						]
					},
					{
						"serialNumber": "8",
						"name": "匹兹堡睡眠质量指数（PSQI）",
						"title": "近1个月，您常感到困倦吗？",
						"itemList": [
							{ "number": "A", "answer": "无" },
							{ "number": "B", "answer": "<1次/周" },
							{ "number": "C", "answer": "1-2次/周" },
							{ "number": "D", "answer": "≥3次/周" }
						]
					},
					{
						"serialNumber": "9",
						"name": "匹兹堡睡眠质量指数（PSQI）",
						"title": "近1个月您做事情的精力不足吗？",
						"itemList": [
							{ "number": "A", "answer": "没有" },
							{ "number": "B", "answer": "偶尔有" },
							{ "number": "C", "answer": "有时有" },
							{ "number": "D", "answer": "经常有" }
						]
					}
				],
				useranswers: {
					"user_id": "1",
					"idd":"",
					"answers": {
						"q1": 22,
						"q2": 1,
						"q3": 10,
						"q4": 8,
						"q5a": 0,
						"q5b": 1,
						"q5c": 2,
						"q5d": 3,
						"q5e": 0,
						"q5f": 1,
						"q5g": 2,
						"q5h": 3,
						"q5i": 0,
						"q5j": 1,
						"q6": 2,
						"q7": 1,
						"q8": 2,
						"q9": 3
					}
				},
				pickerIndex: 0,
				pickerRange: [],
				progress: 0,
				currentPoints: 0,
				isShare: 3,
				userinfo: {}, // 初始化为空对象
				showMessage: { // 初始化为空对象
					total_score: 0,
					sleep_quality: '',
					component_scores: {}
				},
				componentScoreLabels: {
					'A': '睡眠质量',
					'B': '入睡时间',
					'C': '睡眠时间',
					'D': '睡眠效率',
					'E': '睡眠障碍',
					'F': '催眠药物',
					'G': '日渐功能障碍'
				},
			
			};
		},
		onShareAppMessage(res) {
			return {
				title: '我已完成答题，快来参与吧'
			};
		},
		onLoad(options) {
			// options 是一个对象，包含传递的所有参数
			const idd = options.id;  // 获取传递的 id 参数
			console.log('传递过来的 id:', idd);
			this.useranswers.idd=idd
			const that = this;
			uni.getSystemInfo({
				success: function(res) {
					that.getHeight = res.windowHeight;
				}
			});
			setTimeout(function() {
				that.loading = true;
			}, 300);

			this.getData();
			this.initPickerRange();
		},
		watch: {
			progress(val) {
				console.log(this.progress + '% - 进度');

				if (this.progress == 100) {
					console.log("答题结束啦");
					console.log(this.useranswers)
					uni.request({
					    url: 'http://202.127.200.31:30010/scale/calculate_psqi', // 请求的URL
					    method: 'POST',
					    data: this.useranswers, // 发送的数据，这里使用的是组件中的useranswers数据
					    header: {
					        'Content-Type': 'application/json' // 设置请求头为JSON格式
					    },
					    success: (res) => {
					        console.log('提交成功:', res.data);
					        this.showMessage = res.data; // 将返回的数据保存到组件的showMessage中
							uni.removeStorageSync('timucach');
							uni.removeStorageSync('numcach');
					    },
					    fail: (err) => {
					        console.error('提交失败:', err);
					    }
					});
					
					this.noData = true;
					this.hasData = false;
					setTimeout(() => {
						this.show = true;
					}, 1300);
				}
			}
		},
		mounted() {
		    // 获取用户信息
		    this.userinfo = uni.getStorageSync("userinfo");
		    if (this.userinfo && this.userinfo.data && this.userinfo.data.userid) {
		        this.useranswers.user_id = this.userinfo.data.userid;
		    }
		    console.log(this.userinfo);
		
		    // 获取缓存的题目和答案数据
		    let numcach = uni.getStorageSync("numcach");
		    let timucach = uni.getStorageSync("timucach");
			
		    // 检查数据是否完整
		    if (numcach && timucach) {
		        // 显示弹窗询问用户是否恢复进度
		        uni.showModal({
		            title: '提示',
		            content: '检测到您有历史答题未完成，是否恢复之前的答题进度（取消将重新答题）？',
		            success: (res) => { // 使用箭头函数以保持this上下文
		                if (res.confirm) {
		                    console.log('用户点击确定');
		                    this.num = numcach;
		                    this.useranswers = timucach;
		                    console.log("********************************");
		                    console.log(numcach);
		                    console.log(timucach);
		                    console.log("********************************");
		                } else if (res.cancel) {
							uni.removeStorageSync('timucach');
							uni.removeStorageSync('numcach');
		                    console.log('用户点击取消');
		                    // 如果用户取消，可以在此处添加逻辑，例如增加页码，执行动画等
		                    setTimeout(() => {
		                        this.animation = 'animation-slide-left';
		                        this.num=0; // 翻到下一页
		                        setTimeout(() => {
		                            this.mentalListActive = -1;
		                            this.animation = '';
		                        }, 100);
		                    }, 300);
		                }
		            }
		        });
		    } else {
		        // 如果数据不完整，可以选择不做任何事，或者执行其他逻辑，如跳转到登录页面等
				setTimeout(() => {
				    this.animation = 'animation-slide-left';
				    this.num=0; // 翻到下一页
				    setTimeout(() => {
				        this.mentalListActive = -1;
				        this.animation = '';
				    }, 100);
				}, 300);
		    }
		},
		methods: {
			initPickerRange() {
				this.pickerRange = [];
				for (let i = 0; i < 24; i++) {
					this.pickerRange.push(`${i}`);
				}
			},
			pickerChange(e) {
				this.pickerIndex = e.detail.value;
				const questionKey = `q${this.DataList[this.num].serialNumber}`;
				this.useranswers.answers[questionKey] = parseInt(this.pickerRange[this.pickerIndex]);
				this.Toggle(this.pickerIndex);
			},
			answerchoose(serialNumber, daan, number) {
				console.log(serialNumber, daan, number);
				// 假设useranswers是一个全局对象
			
				// 构造问题的键名
				let questionKey = `q${serialNumber}`;
							
				// 检查该问题是否存在于答案对象中
				if (this.useranswers.answers.hasOwnProperty(questionKey)) {
				    // 如果存在，更新答案
					if (questionKey == 'q1') {
						this.useranswers.answers[questionKey] = parseInt(number);
					} else {
						this.useranswers.answers[questionKey] = parseInt(daan);
					}
				    console.log('Answer updated:', questionKey, daan);
				} else {
				    // 如果问题键不存在，打印错误信息
				    console.error('Invalid question serial number:', serialNumber);
				}
			},
			getData() {
				this.progress = 0;
			},
			Toggle(index) {
				// 中途保存
				uni.setStorageSync("numcach", this.num+1);
				uni.setStorageSync("timucach", this.useranswers);
				this.mentalListActive = index;
				console.log(this.num + 1);
				console.log('length:', this.DataList.length);
				this.progress = (100 / this.DataList.length) * (this.num + 1); //进度条

				if (this.progress < 100) {
					setTimeout(() => {
						this.animation = 'animation-slide-left';
						this.num++; //翻第二页
						setTimeout(() => {
							this.mentalListActive = -1;
							this.animation = '';
						}, 100);
					}, 300);
				} else {
					console.log('没有下一题了');
					this.show = true;
				}
			},
			// 弹窗消失
			closeMask() {
				this.show = false;
			},
			goExplain() {
				uni.navigateTo({
					url: './explain'
				});
			},
			formatComponentScores(componentScores) {
				return Object.keys(componentScores).map(key => {
					return `${this.componentScoreLabels[key]}: ${componentScores[key]}分`;
				}).join(', ');
			}
		}
	};
</script>

<style lang="scss" scoped>
	@import '@/colorui/animation.css';

	.warp {
		display: flex;
		align-items: center;
		justify-content: center;
		height: 100%;
	}

	.rect {
		width: 480rpx;
		// height: 520rpx;
		border-radius: 20rpx;
		padding: 25rpx 25rpx 80rpx 25rpx;
		box-sizing: border-box;
		background-color: #fff;
	}

	.closeImg {
		width: 100%;
		height: 200rpx;
		margin: 10rpx auto 30rpx;

		image {
			height: 200rpx;
		}
	}

	.cu-bar .cu-avatar:first-child {
		margin-left: -11px;
	}

	.cu-bar {
		height: 90rpx !important;
	}

	.mainBox {
		padding: 60rpx 40rpx 20rpx 40rpx;
	}

	.explainMain {
		width: 100%;
		text-align: center;
		font-size: 24rpx;
		text-align: center;
		color: #999999;
		margin-top: 30rpx;
	}

	.userHeard {
		position: absolute;
		left: 50%;
		top: -50rpx;
		margin-left: -50rpx;
	}

	.mentalTitle {
		margin: 0 0 30rpx 0;
	}

	.mentalList {
		width: 100%;
		height: 78rpx;
		line-height: 78rpx;
		padding-right: 20rpx;
		border-radius: 12rpx;
		margin: 30rpx 0;
		overflow: hidden;
		border: 1px solid #dddddd;

		.indexBox {
			width: 70rpx;
			height: 78rpx;
			text-align: center;
			line-height: 78rpx;
			float: left;
			background-color: #dddddd;
			margin-right: 15rpx;
		}
	}

	.mentalListActive {
		width: 100%;
		height: 78rpx;
		line-height: 78rpx;
		padding-right: 20rpx;
		border: 1px solid #0081ff;
		border-radius: 12rpx;
		color: #0081ff;
		margin: 30rpx 0;
		font-weight: 600;
		background-image: url(http://cdn.zhoukaiwen.com/answerYes.png);
		background-repeat: no-repeat;
		background-size: 38rpx;
		background-position: right 30rpx center;

		.indexBox {
			background-color: #0081ff;
			color: #ffffff;
		}
	}

	.contaier {
		background-color: #f2f2f2;

		.bannerBox {
			width: 750rpx;

			image {
				width: 750rpx;
			}
		}

		.explain {
			width: 750rpx;
			// position: absolute;
			bottom: 40rpx;
			font-size: 24rpx;
			margin: 10rpx 0 40rpx 0;
			text-align: center;
			color: #999999;

			.integral {
				font-size: 30rpx;
				margin-bottom: 15rpx;
				color: #333333;
			}
		}
	}
</style>